Instead of casting like that, try: allShapes = cubes.Cast().ToList() You need . NET 3.5 for this. I believe the Cast extension method can be found in System.Linq.
Instead of casting like that, try: allShapes = cubes.Cast().ToList(); You need . NET 3.5 for this. I believe the Cast extension method can be found in System.Linq.
1 You beat me to it. – Steven Feb 16 '10 at 11:32 2 Note, this copies the list (albeit if it contains references the references and not the objects will be copied). This is not the same as casting the list object itself.
– Richard Feb 16 '10 at 11:35 @Richard: Great point. – Dave Markle Feb 16 '10 at 12:47 This is as close as you can get in . NET 3.5.There's no way to cast the list object as asked.
– Lasse V. Karlsen? 3.5.1 at 8:58.
You can't. Because List and ILIst to only support invariant type parameters. This is down to T being both use for input and output parameters (e.g. Return values).
Otherwise you can break the type safety. Other interfaces (e.g. IEntumerable) do allow some variance. See Eric Lippert's blog "Fabulous Adventures In Coding" for discussion of contra- and co-variance.
Specifically the "Covariance and Contravariance" tag. Edit, just added to the "C# Frequently Asked Questions" blog: Covariance and Contravariance FAQ.
You cannot do this since by casting this way you can potentially lose all type safety. For instnce, casting List to List will result in that objects of any type can be added to the list, which will be downright inconsistent.
What you are referring to is called generic covariance and is not supported by c# 3. It is, however, supported by c# 4 (.NET 4 / VS 2010) and you can read more about it here: Variance in Generic Interfaces Having said that, IList is not covariant (because it both accepts and exposes T). IEnumerable, on the other hand, is covariant (because it doesn't accept T).
You can also do: allShapes = cubes. ConvertAll(x => (Shape)x); Or if you are doing this in . NET 2.0: allShapes = cubes.
ConvertAll(delegate(Cube c){ return (Shape)c; }).
You can't cast between lists of types, even if the types themselves are convertible. You will need to create a new list and populate it, either by iterating the original list or by using ConvertAll. See dev102.com/2008/05/15/how-to-convert-lis... for sample code.
This works if you define allShapes as IEnumerable In C# 4.0 you may simply assign allshapes=cubes For C# 3.5 you could use allShapes = cubes. Select(c=>((Shape)c)); But in any case you need to use IEnumerable instead of List.
I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.